#!/usr/bin/env bash
#
# Initializing new factory

set -e

VPC_ID='vpc-0835f969191b633cc'
LISTENER_ARN='arn:aws-cn:elasticloadbalancing:cn-northwest-1:190817836750:listener/app/lake/e4511d683e88c67d/1084752ef1138f45'

AWS='aws --no-cli-pager --region cn-northwest-1'
MYSQL='mysql --defaults-group-suffix=.lk.admin'
REDIS='redis-cli -p 6319'

if [ $# -lt 3 ]; then
	echo "Usage: ./deploy.sh <no> <code> <name>"
	exit
fi

export NO=$1
export CODE=$2
export NAME=$3

DOMAIN="${CODE}.haishenxiyi.net"

APPLICATION="lake"
MODULE="${CODE}"
PROFILE="master"

LT_ID="lt-0a0de3916921f3233"
AUTO_SCALING_GROUP="${APPLICATION}-${MODULE}-${PROFILE}"

REDIS_DB=${NO}
REDIS="${REDIS} -n ${REDIS_DB}"

DB_NAME="lk_${CODE}"
DB_USER="${CODE}"
DB_PASS=$(LC_ALL=C tr -dc a-zA-Z0-9 < /dev/urandom | head -c 16)

IFS=$'\t' read -r -a SUBNETS <<< $(
	$AWS ec2 describe-subnets \
		--filters \
			Name=vpc-id,Values=${VPC_ID} \
			Name=tag:Name,Values='lake-private-*' \
		--output text \
		--query 'Subnets[].SubnetId'
)
echo "Subnets: ${SUBNETS[@]}"

TARGET_GROUP_ARN=$(
$AWS elbv2 create-target-group \
	--output text \
	--name "${APPLICATION}-${MODULE}-${PROFILE}" \
	--protocol HTTP \
	--port 8080 \
	--vpc-id "${VPC_ID}" \
	--health-check-path '/api/noop' \
	--health-check-interval-seconds 5 \
	--health-check-timeout-seconds 2 \
	--healthy-threshold-count 2 \
	--unhealthy-threshold-count 2 \
	--matcher HttpCode="200\,204" \
	--target-type instance \
	--tags "Key=Application,Value=${APPLICATION}" "Key=Module,Value=${MODULE}" "Key=Profile,Value=${PROFILE}" \
	--query 'TargetGroups[0].TargetGroupArn'
)
echo "Target Group ARN: ${TARGET_GROUP_ARN}"

${AWS} elbv2 modify-target-group-attributes \
	--target-group-arn ${TARGET_GROUP_ARN} \
	--attributes \
		Key=deregistration_delay.timeout_seconds,Value=5 \
	--output text

PRIORITY=$(( ${NO} * 10 ))

RULE_ARN=$(
$AWS elbv2 create-rule \
	--listener-arn ${LISTENER_ARN} \
	--priority ${PRIORITY} \
	--conditions "Field=host-header,Values=${DOMAIN}" \
	--actions Type=forward,TargetGroupArn=${TARGET_GROUP_ARN} \
	--tags "Key=Name,Value=${NAME}" \
	--output text \
	--query 'Rules[0].RuleArn'
)
echo "Rule Priority: ${PRIORITY}"
echo "Rule ARN: ${RULE_ARN}"

$AWS s3 cp "s3://deploy.dajingxiapp.com/${APPLICATION}/${PROFILE}.yml" - |
	CODE="${CODE}" DB_PASS="${DB_PASS}" REDIS_DB="${REDIS_DB}" \
yq '.lakeworks.app = strenv(CODE) | .lakeworks.jdbc.password = strenv(DB_PASS) | .spring.redis.database = env(REDIS_DB)' |
$AWS s3 cp - "s3://deploy.dajingxiapp.com/${APPLICATION}/${MODULE}/${PROFILE}.yml" --content-type 'application/yaml'

$AWS s3 cp "s3://deploy.dajingxiapp.com/${APPLICATION}/${MODULE}/${PROFILE}.yml" -

$MYSQL -e'
	CREATE DATABASE `'${DB_NAME}'` DEFAULT CHARSET utf8mb4;
	CREATE USER `'${DB_USER}'`@`172.19.%` IDENTIFIED BY '\'"${DB_PASS}"\'';
	GRANT SELECT ON `'${DB_NAME}'`.* TO `ro`@`172.18.%`;
	GRANT ALL ON `'${DB_NAME}'`.* TO `'${DB_USER}'`@`172.19.%`;
	SHOW GRANTS FOR`'${DB_USER}'`@`172.19.%`;
'

$MYSQL "${DB_NAME}" < lake.ddl
$MYSQL "${DB_NAME}" < lake.sql
$MYSQL "${DB_NAME}" < ticket.sql

$MYSQL --column-names=false "${DB_NAME}" -e'SELECT `no` FROM `sys_frame` WHERE NOT `is_attachment`' |
while read NO; do
	echo $(( $(printf %d \'${NO::1}) - 65 ))'.'${NO:1} ${NO}
done | xargs $REDIS zadd "frame:noAtt"

$MYSQL --column-names=false "${DB_NAME}" -e'SELECT `no` FROM `sys_frame` WHERE `is_attachment`' |
while read NO; do
	echo $(( $(printf %d \'${NO::1}) - 65 ))'.'${NO:1} ${NO}
done | xargs $REDIS zadd "frame:isAtt"

${AWS} autoscaling create-auto-scaling-group \
	--auto-scaling-group-name ${AUTO_SCALING_GROUP}\
	--launch-template LaunchTemplateId=${LT_ID} \
	--min-size 1 \
	--max-size 2 \
	--desired-capacity 1 \
	--health-check-type ELB \
	--health-check-grace-period 30 \
	--vpc-zone-identifier $(echo ${SUBNETS[@]} | sed 's/ /,/g') \
	--termination-policies OldestInstance \
	--no-new-instances-protected-from-scale-in \
	--default-instance-warmup 30 \
	--traffic-sources Identifier=${TARGET_GROUP_ARN},Type=elbv2 \
	--instance-maintenance-policy MinHealthyPercentage=100,MaxHealthyPercentage=200 \
	--tags \
		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Application,Value=${APPLICATION},PropagateAtLaunch=True \
		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Module,Value=${MODULE},PropagateAtLaunch=True \
		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Profile,Value=${PROFILE},PropagateAtLaunch=True \
		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Version,Value=${VERSION},PropagateAtLaunch=True
